package com.so.framework.config;

import com.baomidou.mybatisplus.annotation.IEnum;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import lombok.Data;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * 枚举反序列化处理类
 * 如果我们接收的是 JSON 字符串类型，那么 Jackson 默认是根据下标进行转换的
 * 和我们根据匹配值获取相应枚举不符，所以进行以下更改
 * @author system
 */
@Data
public class EnumDeserializer extends JsonDeserializer<Enum<?>> implements ContextualDeserializer {

    private Class<?> target;

    @Override
    public Enum<?> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        if (!StringUtils.hasText(jsonParser.getText())) {
            return null;
        }
        if (IEnum.class.isAssignableFrom(target)) {
            return (Enum<?>) EnumConvertFactory.getEnum((Class) target, jsonParser.getText());
        }
        return defaultEnumTransform(target,jsonParser.getText());

    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctx, BeanProperty beanProperty) throws JsonMappingException {
        Class<?> rawCls = ctx.getContextualType().getRawClass();
        EnumDeserializer enumDeserializer = new EnumDeserializer();
        enumDeserializer.setTarget(rawCls);
        return enumDeserializer;
    }

    public static Enum<?> defaultEnumTransform(Class<?> type, String indexString) {
        Enum<?>[] enumConstants = (Enum<?>[]) type.getEnumConstants();
        try {
            int index = Integer.parseInt(indexString);
            return enumConstants[index];
        } catch (NumberFormatException e) {
            return null;
        }
    }

}
